package com.lanou.zakerproject.community;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanou.zakerproject.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.util.ArrayList;

//http://blog.csdn.net/xiaanming/article/details/26810303

public class CommentActivity extends AppCompatActivity {
    private static final int REQUEST_PICK = 0;
    private GridView gridview;
    private GridAdapter adapter;
    private ArrayList<String> selectedPicture = new ArrayList<String>();
    private String ADDPIC = "add";
    private LayoutInflater inflater;
    private TextView title;
    private Button btn_titleright;
    private DisplayImageOptions options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                this)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .memoryCache(new WeakMemoryCache())
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .imageDownloader(new BaseImageDownloader(this, 10000, 60000))
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
                .discCacheFileCount(100) // 缓存的文件数量
                .build();
        ImageLoader.getInstance().init(config);
        options = new DisplayImageOptions.Builder()
                .resetViewBeforeLoading(true).cacheOnDisc(true)
                .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(true)
                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)
                        // 设置下载的图片是否缓存在SD卡中
                .bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new FadeInBitmapDisplayer(300)).build();
        selectedPicture.add(ADDPIC);
        gridview = (GridView) findViewById(R.id.gridview);
        adapter = new GridAdapter();
        gridview.setAdapter(adapter);
        inflater = LayoutInflater.from(this);
        title = (TextView) findViewById(R.id.tv_titletext);
        LinearLayout btn_back = (LinearLayout) findViewById(R.id.ll_tback);
        title.setText("添加评论");
        btn_back.setVisibility(View.VISIBLE);
        btn_titleright = (Button) findViewById(R.id.btn_titleright);
        btn_titleright.setVisibility(View.VISIBLE);
        btn_titleright.setText("提交");
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String temp = selectedPicture.get(position);
                if (temp.equals(ADDPIC)) {
                    Intent intent = new Intent(
                            CommentActivity.this,
                            SelectPictureActivity.class);
                    int max = 4 - selectedPicture.size() + 1;
                    intent.putExtra(
                            SelectPictureActivity.INTENT_MAX_NUM,
                            max);
                    startActivityForResult(intent, REQUEST_PICK);
                }
            }
        });
        gridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                String temp = selectedPicture.get(position);
                if (!temp.equals(ADDPIC)) {
                    dialog(position);
                }
                return false;
            }
        });
    }

    public void dialog(final int index) {
        AlertDialog.Builder builder = new AlertDialog.Builder(CommentActivity.this);
        builder.setMessage("确认删除么？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                selectedPicture.remove(index);
                if (selectedPicture.size() < 4 && !selectedPicture.contains(ADDPIC)) {
                    selectedPicture.add(ADDPIC);
                }
                adapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    public void selectedPicture(View view) {
        startActivityForResult(new Intent(this, SelectPictureActivity.class), REQUEST_PICK);
    }

    /**
     * J2SE 提供的最后一个批注是 @SuppressWarnings。
     * 该批注的作用是给编译器一条指令，告诉它对被批注的代码元素内部的某些警告保持静默。
     * unchecked 执行了未检查的转换时的警告，例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型。
     */

    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            ArrayList<String> temp = (ArrayList<String>) data
                    .getSerializableExtra(SelectPictureActivity.INTENT_SELECTED_PICTURE);
            selectedPicture.addAll(selectedPicture.size() - 1, temp);
            if (selectedPicture.size() > 4) {
                selectedPicture.remove(ADDPIC);
            }
            adapter.notifyDataSetChanged();
        }
    }

    class GridAdapter extends BaseAdapter {
        LayoutParams params = new AbsListView.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        @Override
        public int getCount() {
            return selectedPicture.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.item_p, null);
            ImageView iv = (ImageView) convertView.findViewById(R.id.iv_pic);
            String path = selectedPicture.get(position);
            if (!TextUtils.isEmpty(path) && path.equals(ADDPIC)) {
                iv.setImageResource(R.mipmap.icon_addpic_unfocused);
            } else {
                ImageLoader.getInstance().displayImage("file://" + path, iv, options, null);
            }
            return convertView;
        }

    }
}
